<template>
  <div class="qa-container">
    <!-- 头部 -->
    <div class="qa-header">
      <div class="header-content">
        <div class="header-left">
          <div class="header-icon">🤖</div>
          <div class="header-info">
            <h2>智能问答助手</h2>
            <p>基于AI和知识库的智能客服系统</p>
          </div>
        </div>
        <div class="header-actions">
          <el-button 
            @click="handleNewDialog" 
            :icon="Refresh" 
            size="default"
            circle
            title="新建对话"
          />
          <el-button 
            @click="handleClearHistory" 
            :icon="Delete" 
            size="default"
            circle
            title="清空历史"
            :disabled="messages.length === 0"
          />
        </div>
      </div>
    </div>

    <!-- 主内容区 -->
    <div class="qa-main">
      <!-- 消息列表 -->
      <div class="messages-container" ref="messagesContainer">
        <div v-if="messages.length === 0" class="empty-state">
          <div class="empty-icon">💬</div>
          <h3>开始对话</h3>
          <p>问我任何问题，我会尽力帮助您</p>
          <div class="suggestions">
            <div class="suggestion-title">您可以试试：</div>
            <div class="suggestion-list">
              <div 
                v-for="suggestion in suggestions" 
                :key="suggestion"
                class="suggestion-item"
                @click="sendSuggestion(suggestion)"
              >
                {{ suggestion }}
              </div>
            </div>
          </div>
        </div>

        <div v-else class="messages-list">
          <div
            v-for="(message, index) in messages"
            :key="index"
            class="message-item"
            :class="{ 'message-user': message.role === 'user', 'message-assistant': message.role === 'assistant' }"
          >
            <div class="message-avatar">
              <span v-if="message.role === 'user'">👤</span>
              <span v-else>🤖</span>
            </div>
            <div class="message-content">
              <div class="message-text" v-html="formatMessage(message.content)"></div>
              <div class="message-time">{{ formatTime(message.created_at || Date.now()) }}</div>
            </div>
          </div>

          <!-- 加载中 -->
          <div v-if="isLoading" class="message-item message-assistant">
            <div class="message-avatar">🤖</div>
            <div class="message-content">
              <div class="message-text loading">
                <span class="loading-dot"></span>
                <span class="loading-dot"></span>
                <span class="loading-dot"></span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 输入区 -->
      <div class="input-container">
        <div class="input-toolbar">
          <el-checkbox v-model="useKnowledgeBase" label="使用知识库" />
          <el-checkbox v-model="useHybridSearch" label="混合检索" :disabled="!useKnowledgeBase" />
        </div>
        <div class="input-wrapper">
          <el-input
            v-model="inputMessage"
            type="textarea"
            :rows="3"
            placeholder="输入您的问题..."
            @keydown.ctrl.enter="sendMessage"
            @keydown.meta.enter="sendMessage"
            :disabled="isLoading"
            resize="none"
            class="message-input"
          />
          <el-button
            type="primary"
            @click="sendMessage"
            :loading="isLoading"
            :disabled="!inputMessage.trim() || isLoading"
            class="send-button"
          >
            发送
          </el-button>
        </div>
        <div class="input-hint">
          <span>按 Ctrl+Enter 或 Cmd+Enter 发送</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted, nextTick, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Refresh, Delete } from '@element-plus/icons-vue'
import { qaAPI } from '../api/index'

export default {
  name: 'QA',
  components: {
    Refresh,
    Delete
  },
  setup() {
    const messagesContainer = ref(null)
    const messages = ref([])
    const inputMessage = ref('')
    const isLoading = ref(false)
    const userId = ref(null)
    const useKnowledgeBase = ref(true)
    const useHybridSearch = ref(true)

    const suggestions = [
      '你好，你能帮我什么？',
      '介绍一下你们的产品',
      '如何预订旅游景点？',
      '有什么优惠政策吗？'
    ]

    // 初始化对话
    const initDialog = async () => {
      try {
        const response = await qaAPI.newDialog()
        userId.value = response.user_id
        // 加载历史记录
        await loadHistory()
      } catch (error) {
        console.error('初始化对话失败:', error)
        // 如果初始化失败，不阻止用户使用，在发送第一条消息时会自动创建user_id
        // 只在控制台记录错误，不显示给用户
        if (error.response?.status === 404) {
          console.warn('QA服务未找到，请确保后端服务正在运行')
        }
      }
    }

    // 加载历史记录
    const loadHistory = async () => {
      if (!userId.value) return
      
      try {
        const response = await qaAPI.getHistory(userId.value)
        messages.value = response.messages.map(msg => ({
          ...msg,
          created_at: msg.created_at || Date.now()
        }))
        // 滚动到底部
        await nextTick()
        scrollToBottom()
      } catch (error) {
        // 404表示没有历史记录，这是正常的
        if (error.response?.status !== 404) {
          console.error('加载历史记录失败:', error)
        }
      }
    }

    // 发送消息
    const sendMessage = async () => {
      const message = inputMessage.value.trim()
      if (!message || isLoading.value) return

      // 添加用户消息到列表
      messages.value.push({
        role: 'user',
        content: message,
        created_at: Date.now()
      })

      // 清空输入框
      inputMessage.value = ''
      
      // 滚动到底部
      await nextTick()
      scrollToBottom()

      // 设置加载状态
      isLoading.value = true

      try {
        // 调用API
        const response = await qaAPI.chat({
          message: message,
          user_id: userId.value,
          use_knowledge_base: useKnowledgeBase.value,
          use_hybrid_search: useHybridSearch.value
        })

        // 更新userId（如果后端返回了新的）
        if (response.user_id) {
          userId.value = response.user_id
        }

        // 添加助手回复
        messages.value.push({
          role: 'assistant',
          content: response.message,
          created_at: Date.now(),
          source: response.source
        })

        // 滚动到底部
        await nextTick()
        scrollToBottom()
      } catch (error) {
        console.error('发送消息失败:', error)
        
        // 提供更详细的错误信息
        let errorMessage = '发送消息失败，请重试'
        
        // 处理超时错误
        if (error.code === 'ECONNABORTED' || error.message?.includes('timeout')) {
          errorMessage = '请求超时，AI处理可能需要更长时间。请稍后重试，或检查网络连接。'
          ElMessage({
            message: errorMessage,
            type: 'warning',
            duration: 5000,
            showClose: true
          })
        } else if (error.response) {
          // 有响应但状态码不是2xx
          if (error.response.status === 404) {
            errorMessage = 'QA服务未找到，请确保后端服务正在运行并已启动QA路由'
          } else if (error.response.status === 401) {
            errorMessage = '认证失败，请重新登录'
          } else if (error.response.status === 500) {
            errorMessage = '服务器处理失败，可能是AI服务异常，请稍后重试'
          } else if (error.response.data?.detail) {
            errorMessage = error.response.data.detail
          } else {
            errorMessage = `请求失败 (${error.response.status})`
          }
          ElMessage.error(errorMessage)
        } else if (error.request) {
          // 请求已发送但没有收到响应
          errorMessage = '无法连接到服务器，请检查后端服务是否运行'
          ElMessage.error(errorMessage)
        } else {
          ElMessage.error(errorMessage)
        }
        
        // 移除用户消息（可选，或者保留并显示错误）
        // messages.value.pop()
      } finally {
        isLoading.value = false
      }
    }

    // 发送建议
    const sendSuggestion = (suggestion) => {
      inputMessage.value = suggestion
      sendMessage()
    }

    // 新建对话
    const handleNewDialog = async () => {
      try {
        await ElMessageBox.confirm(
          '确定要新建对话吗？当前对话历史将被保存。',
          '新建对话',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'info'
          }
        )
        
        const response = await qaAPI.newDialog()
        userId.value = response.user_id
        messages.value = []
        ElMessage.success('已创建新对话')
      } catch (error) {
        if (error !== 'cancel') {
          console.error('新建对话失败:', error)
          ElMessage.error('新建对话失败')
        }
      }
    }

    // 清空历史
    const handleClearHistory = async () => {
      if (!userId.value) return

      try {
        await ElMessageBox.confirm(
          '确定要清空对话历史吗？此操作不可恢复。',
          '清空历史',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )

        await qaAPI.deleteHistory(userId.value)
        messages.value = []
        ElMessage.success('历史记录已清空')
      } catch (error) {
        if (error !== 'cancel') {
          console.error('清空历史失败:', error)
          ElMessage.error('清空历史失败')
        }
      }
    }

    // 格式化消息（支持换行）
    const formatMessage = (text) => {
      if (!text) return ''
      return text.replace(/\n/g, '<br>')
    }

    // 格式化时间
    const formatTime = (timestamp) => {
      if (!timestamp) return ''
      const date = new Date(timestamp)
      const now = new Date()
      const diff = now - date

      if (diff < 60000) {
        return '刚刚'
      } else if (diff < 3600000) {
        return `${Math.floor(diff / 60000)}分钟前`
      } else if (diff < 86400000) {
        return `${Math.floor(diff / 3600000)}小时前`
      } else {
        return date.toLocaleString('zh-CN', {
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit'
        })
      }
    }

    // 滚动到底部
    const scrollToBottom = () => {
      if (messagesContainer.value) {
        messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
      }
    }

    // 组件挂载时初始化
    onMounted(() => {
      initDialog()
    })

    return {
      messagesContainer,
      messages,
      inputMessage,
      isLoading,
      useKnowledgeBase,
      useHybridSearch,
      suggestions,
      sendMessage,
      sendSuggestion,
      handleNewDialog,
      handleClearHistory,
      formatMessage,
      formatTime
    }
  }
}
</script>

<style scoped>
.qa-container {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f5f5;
}

.qa-header {
  background: white;
  border-bottom: 1px solid #e0e0e0;
  padding: 16px 24px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.header-icon {
  font-size: 32px;
}

.header-info h2 {
  margin: 0;
  font-size: 20px;
  color: #333;
}

.header-info p {
  margin: 4px 0 0 0;
  font-size: 14px;
  color: #666;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.qa-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  max-width: 1200px;
  width: 100%;
  margin: 0 auto;
  padding: 24px;
  overflow: hidden;
}

.messages-container {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background: white;
  border-radius: 8px;
  margin-bottom: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  padding: 40px 20px;
  text-align: center;
}

.empty-icon {
  font-size: 64px;
  margin-bottom: 16px;
}

.empty-state h3 {
  margin: 0 0 8px 0;
  font-size: 24px;
  color: #333;
}

.empty-state p {
  margin: 0 0 32px 0;
  color: #666;
  font-size: 16px;
}

.suggestions {
  width: 100%;
  max-width: 600px;
}

.suggestion-title {
  font-size: 14px;
  color: #999;
  margin-bottom: 12px;
}

.suggestion-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.suggestion-item {
  padding: 12px 16px;
  background: #f5f5f5;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s;
  text-align: left;
}

.suggestion-item:hover {
  background: #e8e8e8;
  transform: translateX(4px);
}

.messages-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.message-item {
  display: flex;
  gap: 12px;
  animation: fadeIn 0.3s ease-in;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.message-user {
  flex-direction: row-reverse;
}

.message-user .message-content {
  align-items: flex-end;
}

.message-assistant .message-content {
  align-items: flex-start;
}

.message-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  flex-shrink: 0;
  background: #f5f5f5;
}

.message-user .message-avatar {
  background: #409eff;
}

.message-content {
  max-width: 70%;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.message-text {
  padding: 12px 16px;
  border-radius: 12px;
  line-height: 1.6;
  word-wrap: break-word;
  white-space: pre-wrap;
}

.message-user .message-text {
  background: #409eff;
  color: white;
  border-bottom-right-radius: 4px;
}

.message-assistant .message-text {
  background: #f5f5f5;
  color: #333;
  border-bottom-left-radius: 4px;
}

.message-text.loading {
  background: #f5f5f5;
  padding: 16px;
  display: flex;
  gap: 4px;
  align-items: center;
}

.loading-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #999;
  animation: loadingDot 1.4s infinite ease-in-out;
}

.loading-dot:nth-child(2) {
  animation-delay: 0.2s;
}

.loading-dot:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes loadingDot {
  0%, 80%, 100% {
    transform: scale(0.8);
    opacity: 0.5;
  }
  40% {
    transform: scale(1);
    opacity: 1;
  }
}

.message-time {
  font-size: 12px;
  color: #999;
  padding: 0 4px;
}

.input-container {
  background: white;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.input-toolbar {
  display: flex;
  gap: 16px;
  margin-bottom: 12px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f0f0f0;
}

.input-wrapper {
  display: flex;
  gap: 12px;
  align-items: flex-end;
}

.message-input {
  flex: 1;
}

.send-button {
  height: 80px;
  padding: 0 24px;
}

.input-hint {
  margin-top: 8px;
  font-size: 12px;
  color: #999;
  text-align: center;
}

/* 滚动条样式 */
.messages-container::-webkit-scrollbar {
  width: 6px;
}

.messages-container::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.messages-container::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.messages-container::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>

